<template>
    <div class="app-container">
        <!-- 提示页面 -->
        <el-card class="tip">
            <h3 class="title">{{ form.subjectName}}</h3>
            <p class="desc">总分:{{form.examTotal }}  时长:{{ form.examTime}}分钟</p>
            <el-divider></el-divider>
            <!-- 这边会根据题目数，以及是否完成进行不同的tag渲染 -->
            <div>
                <span v-for="item,index in userAnswer.answers" :key="index" >
                    <el-tag type="info" @click="goAnchor('#question-'+(index))" class="exam-tag" v-if="item.completed ==false">{{ index+1}}</el-tag>
                    <el-tag type="primary" @click="goAnchor('#question-'+(index))" class="exam-tag" v-if="item.completed ==true">{{ index+1}}</el-tag>
                </span>
            </div>
            <el-divider></el-divider>
            <p class="surplus-time">
                <span>剩余时间：</span>
                <span style="display: block; color: red; font-size: 20px;">{{ formatTimes(remainTime)}}</span>
            </p>
            <el-divider></el-divider>
            <p>
                <el-button type="primary" class="submit" @click="submitExam">提交试卷</el-button>
            </p>
        </el-card>
        <div class="question" v-for="item,index in form.question" :key="item.id" :id="'question-'+index">
            <QuestionEdit :questionItem="item" :index="(index+1)+'、'" :answerItem="userAnswer.answers[index]"></QuestionEdit>
            <el-divider></el-divider>
        </div>
    </div>
</template>

<script>
import QuestionEdit from '@/views/exam/questionEdit'
import { getQuestionList,correctExam } from '@/api/exam/exam';
export default {
    name:'ExamPaper',
    components:{
        QuestionEdit
    },
    data(){
        return{
            form:{
                // 试卷的id
                id:null,
                subjectName:'',
                examTime:null, //单位分钟
                examTotal:null,
                question:[]
            },
            remainTime:0,
            //定时器
            timer:null,
            userAnswer:{
                // 用时
                doTime:0,
                examId:null,
                answers:[]
            },
            score:'',
        }
    },
    beforeDestroy(){
        clearInterval(this.timer);
        console.log('开始提交');
    },
    created(){
        console.log('考试进行页面被加载');
        let examId = this.$route.params.id;
        let subjectName = this.$route.params.subjectName;
        let endTime = this.$route.params.endTime;
        let examTime = this.$route.params.examTime;
        let examTotal = this.$route.params.examTotal;
        if(examId && parseInt(examId) != 0){
            this.form.id = examId;
            this.form.subjectName = subjectName;
            this.form.examTime = examTime;
            let end = Date.parse(endTime);
            let now = new Date().getTime();
            this.remainTime = Math.ceil((end-now)/1000);
            this.form.examTotal = examTotal;
            this.userAnswer.examId = examId;
            getQuestionList(examId).then(resp=>{
                this.form.question = resp.data;
                // 倒计时
                this.timeReduce();
                //初始化答案
                this.initAnswer();
            })
        }else{
            return;
        }
    },
    methods:{
        //初始化答案
        initAnswer(){
            // 在这里将多选题以数组的形式转换
            this.form.question.forEach(el=>{
                this.userAnswer.answers.push({questionId:el.id,answer:'',answerList:[],completed:false})
            })
        },
        submitExam(){
            if(this.remainTime <= 0){
                this.submit();
            }else{
                this.$confirm('是否确认交卷？',{
                    confirmButtonText:'确认交卷',
                    cancelButtonText:'取消交卷',
                    type:'info'
                }).then(()=>{
                    this.submit();
                }).catch(()=>{

                })
            }
        },
        submit(){
            // 这边将数据进行提交
            clearInterval(this.timer)
            correctExam(this.userAnswer).then(resp =>{
                this.$alert(`考试结束，系统得分：${resp.data}`,{
                    confirmButtonText:'确定',
                    callback: action=>{
                        this.$router.push('/exam/index')
                    }
                })
            }).catch(error =>{

            })

        },
        timeReduce(){
            this.timer = setInterval(() => {
                if(this.remainTime <= 0){
                    this.submitExam();
                    return;
                }
                if(this.remainTime == (15 *60)){
                    this.$message.info("离考试还有15分钟结束")
                }
                --this.remainTime;
                ++this.userAnswer.doTime;
            }, 1000);
        },
        // 格式化时间
        formatTimes(val){
            let hours = Math.floor(val / 60 / 60);
            let mins = Math.floor((val - (hours * 3600) )/ 60);
            let seconds = val % 60;
            return this.format(hours)+':'+this.format(mins)+':'+this.format(seconds)
        },
        format(val){
            if(val < 10){
                return '0'+val;
            }
            return val;
        },
        goAnchor(selector){
            this.$el.querySelector(selector).scrollIntoView({ behavior: 'instant', block: 'center', inline: 'nearest' })
        },
    }
}
</script>

<style scoped>
    *{
        margin: 0px;
        padding: 0px;
    }
    a{
        text-decoration: none;
        font-size: 14px;
        color: #409Eff;
    }
    .desc{
        font-size: 14px;
        margin-bottom: 5px;
    }
    .app-container{
        padding: 30px 20px;
    }
    .tip{
        width: 20%;
        height: 100%;
        position: fixed;
        
    }
    .question{
        width: 75%;
        margin-left: 22%;
        border: none;
    }
    .title{
        font-family: '楷体';
        margin-bottom: 15px;
    }
    .exam-tag{
        height: 30px;
        width: 30px;
        margin: 5px 0px 5px 5px;
        line-height: 25px;
    }
    .surplus-time{
        margin:15px 0px;
        padding-left: 15px;
        text-align: center;
    }
    .submit{
        width: 90px; 
        height: 30px;
        margin-top: 35px;
    }
    .exam-tag:hover{
        cursor: pointer;
    }
</style>